/**
 * @file eplapsed_timer.hpp
 * @date 2021/08/22 14:08
 * 
 * @author harrybao (harrybao@123u.com)
 * 
 * @brief RAII 打印代码耗时
 * 
 * @version v1.0.0
 * 
 * @par history:
 * <table>
 * <tr><th>Date                     <th>Version     <th>Author      <th>Description
 * <tr><td>2021/08/22 14:08         <td>1.0.0       <td>harrybao    <td>创建初始版本
 * </table>
 */

#pragma once

#include <string>
#include <iostream>
#include <chrono>

namespace timer {
class elapsed_timer {
 public:
  elapsed_timer(const std::string &tag) {  // 对象构造时候保存开始时间
    m_begin = std::chrono::high_resolution_clock::now();
    m_tag = tag;
  }

  void reset() { m_begin = std::chrono::high_resolution_clock::now(); }

  int64_t elapsed() {
    return static_cast<int64_t>(
        std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::high_resolution_clock::now() - m_begin)
            .count());
  }

  ~elapsed_timer() {  // 对象析构时候计算当前时间与对象构造时候的时间差就是对象存活的时间
    auto time = std::chrono::duration_cast<std::chrono::milliseconds>(
                    std::chrono::high_resolution_clock::now() - m_begin)
                    .count();
    std::cout << "time { " << m_tag << " } " << static_cast<double>(time)
              << " ms" << std::endl;
  }

 private:
  std::chrono::time_point<std::chrono::high_resolution_clock> m_begin;
  std::string m_tag;
};

}  // namespace timer